package com.dkd.flow.rules;
import com.alibaba.fastjson2.JSONObject;
import com.dkd.flow.rules.empty.EmptyRule;
import com.dkd.flow.rules.initiator.InitiatorRule;
import com.dkd.flow.rules.conditions.ConditionsRule;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static com.dkd.framework.datasource.DynamicDataSourceContextHolder.log;
@Component
@Service
public class BaseRules {
    //注入的实例，不需要清空 --- start ---//
    @Autowired
    InitiatorRule initiatorRule;
    @Autowired
    ConditionsRule conditionsRule;
    @Autowired
    EmptyRule emptyRule;
    //注入的实例，不需要清空 --- end ---//
    Rules rules = null;
    public ArrayList<JSONObject> ruleResult = new ArrayList<>();
    public JSONObject formData;
    void clear() {
        ruleResult.clear();
        rules = null;
        formData = null;
    }
    public void register(JSONObject _formData) {
        this.clear();
        rules = new Rules();
        rules.register(initiatorRule, conditionsRule, emptyRule);
        formData = _formData;
    }
    public void fire(JSONObject node) {
        if (rules != null) {
            Facts facts = new Facts();
            facts.put("node", node);
            RulesEngine rulesEngine = new DefaultRulesEngine();
            rulesEngine.fire(rules, facts);
        } else {
            throw new RuntimeException("rules is null：规则引擎未注册");
        }
    }
    //处理结果，最后调用
    public String resultPick() {
        log.info("resultPick", ruleResult);
        Map<String, ArrayList<Boolean>> map = new HashMap<>();
        Map<String, Integer> priorityMap = new HashMap<>(); // 新增：用于存储每个节点的优先级
        ruleResult.stream()
                .forEach(item -> {
                    String nodeId = item.getString("nodeId");
                    if (map.get(nodeId) == null) {
                        map.put(nodeId, new ArrayList<Boolean>());
                    }
                    map.get(nodeId)
                            .add(item.getBooleanValue("result"));
                    // 新增：记录每个节点的优先级
                    if (!priorityMap.containsKey(nodeId)) {
                        priorityMap.put(nodeId, item.getIntValue("priority"));
                    }
                });
        String nodeId = null;
        int lowestPriority = Integer.MAX_VALUE; // 新增：用于记录最低优先级
        for (Map.Entry<String, ArrayList<Boolean>> entry : map.entrySet()) {
            if (entry.getValue()
                    .stream()
                    .allMatch(bool -> bool)) {
                String currentNodeId = entry.getKey();
                int currentPriority = priorityMap.getOrDefault(currentNodeId, Integer.MAX_VALUE);
                if (currentPriority < lowestPriority) {
                    lowestPriority = currentPriority;
                    nodeId = currentNodeId;
                }
            }
        }
        return nodeId;
    }
}